<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>面试记录 - AI智能面试系统</title>
    <link href="/vendors/bootstrap/bootstrap.min.css" rel="stylesheet">
    <link href="/vendors/fontawesome/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #667eea;
            --secondary-color: #764ba2;
            --accent-color: #f093fb;
            --text-dark: #2d3748;
            --text-light: #718096;
            --bg-light: #f7fafc;
        }

        /* 统一导航栏样式 */
        .unified-navbar {
            background: white !important;
            border-bottom: 1px solid #e5e7eb !important;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1) !important;
            position: fixed !important;
            top: 0 !important;
            left: 0 !important;
            z-index: 1000 !important;
            height: 70px !important;
            width: 100% !important;
            margin: 0 !important;
            padding: 0 !important;
        }

        .unified-navbar-container {
            width: 100%;
            padding: 0 24px;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .unified-navbar-left {
            flex-shrink: 0;
        }

        .unified-navbar-brand {
            display: flex;
            align-items: center;
            text-decoration: none;
            color: #1f2937;
            font-weight: 700;
            font-size: 1.5rem;
        }

        .unified-navbar-brand i {
            color: var(--primary-color);
            margin-right: 8px;
            font-size: 1.2rem;
        }

        .unified-navbar-brand:hover {
            color: var(--primary-color);
            text-decoration: none;
        }

        .unified-navbar-center {
            flex: 1;
            display: flex;
            justify-content: center;
        }

        .unified-navbar-menu {
            display: flex;
            align-items: center;
            gap: 40px;
        }

        .unified-navbar-right {
            flex-shrink: 0;
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .unified-nav-item {
            display: flex;
            align-items: center;
            text-decoration: none;
            color: #6b7280;
            font-weight: 500;
            font-size: 14px;
            padding: 8px 12px;
            border-radius: 6px;
            transition: all 0.2s ease;
        }

        .unified-nav-item i {
            margin-right: 6px;
            font-size: 14px;
        }

        .unified-nav-item:hover {
            color: var(--primary-color);
            background: #eff6ff;
            text-decoration: none;
        }

        .unified-nav-item.active {
            color: var(--primary-color);
            background: #eff6ff;
            font-weight: 600;
        }

        .unified-nav-item.user-info {
            background: #f3f4f6;
            color: var(--primary-color);
            font-weight: 600;
            cursor: default;
        }

        .unified-nav-item.user-info:hover {
            background: #f3f4f6;
            color: var(--primary-color);
        }

        @media (max-width: 768px) {
            .unified-navbar-container {
                padding: 0 16px;
            }
            
            .unified-navbar-menu {
                gap: 15px;
            }
            
            .unified-nav-item {
                font-size: 13px;
                padding: 6px 8px;
            }
            
            .unified-navbar-brand {
                font-size: 1.3rem;
            }
        }

        @media (max-width: 576px) {
            .unified-navbar-center {
                display: none;
            }
            
            .unified-navbar-right {
                gap: 10px;
            }
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            margin: 0;
            padding: 80px 20px 20px 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            padding: 40px 30px;
            color: white;
            text-align: center;
            position: relative;
        }
        
        .header h1 {
            font-size: 32px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        
        .back-button {
            position: absolute;
            left: 30px;
            top: 50%;
            transform: translateY(-50%);
            background: rgba(255,255,255,0.1);
            color: white;
            border: 2px solid rgba(255,255,255,0.3);
            border-radius: 25px;
            padding: 8px 16px;
            text-decoration: none;
            transition: all 0.3s ease;
        }
        
        .back-button:hover {
            background: rgba(255,255,255,0.2);
            color: white;
            text-decoration: none;
        }
        
        .content {
            padding: 30px;
        }
        
        .record-card {
            border: 2px solid #e0e0e0;
            border-radius: 15px;
            margin-bottom: 20px;
            overflow: hidden;
            transition: all 0.3s ease;
        }
        
        .record-card:hover {
            border-color: #4facfe;
            transform: translateY(-2px);
        }
        
        .record-header {
            background: #f8f9fa;
            padding: 20px;
            border-bottom: 1px solid #e0e0e0;
            display: grid;
            grid-template-columns: 1fr 1fr 1fr auto;
            gap: 20px;
            align-items: center;
        }
        
        .info-item {
            display: flex;
            flex-direction: column;
        }
        
        .info-label {
            font-size: 12px;
            color: #888;
            margin-bottom: 4px;
        }
        
        .info-value {
            font-size: 14px;
            font-weight: 600;
            color: #333;
        }
        
        .record-actions {
            display: flex;
            gap: 10px;
        }
        
        .btn-expand, .btn-delete, .btn-evaluate, .btn-view-analysis {
            border: none;
            border-radius: 8px;
            padding: 8px 12px;
            font-size: 12px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .btn-expand {
            background: #4facfe;
            color: white;
        }
        
        .btn-delete {
            background: #dc3545;
            color: white;
        }
        
        .btn-evaluate {
            background: #28a745;
            color: white;
        }
        
        .btn-view-analysis {
            background: #17a2b8;
            color: white;
        }
        
        .record-content {
            padding: 0;
            max-height: 0;
            overflow: hidden;
            transition: all 0.5s ease;
        }
        
        .record-content.expanded {
            max-height: none;
            padding: 20px;
        }
        
        .session-details {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        
        .detail-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
        }
        
        .detail-item {
            display: flex;
            flex-direction: column;
        }
        
        .detail-value {
            background: white;
            padding: 8px 10px;
            border-radius: 6px;
            border: 1px solid #e0e0e0;
            font-size: 14px;
        }
        
        .answer-item {
            background: #f8f9fa;
            border: 1px solid #e0e0e0;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
        }
        
        .answer-question {
            font-weight: 600;
            color: #333;
            margin-bottom: 10px;
            padding: 8px 10px;
            background: white;
            border-radius: 6px;
            border-left: 4px solid #4facfe;
        }
        
        .answer-content {
            background: white;
            padding: 12px;
            border-radius: 6px;
            border: 1px solid #e0e0e0;
            line-height: 1.6;
            color: #555;
            white-space: pre-wrap;
        }
        
        .no-records {
            text-align: center;
            padding: 60px 20px;
            color: #888;
        }
        
        .no-records-icon {
            font-size: 64px;
            margin-bottom: 20px;
            opacity: 0.5;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            border: none;
            border-radius: 25px;
            padding: 12px 24px;
            text-decoration: none;
            transition: all 0.3s ease;
        }
        
        .btn-primary:hover {
            color: white;
            text-decoration: none;
            transform: translateY(-2px);
        }
        
        .loading {
            text-align: center;
            padding: 60px 20px;
            color: #888;
        }
    </style>
</head>
<body>
    <!-- 统一导航栏 -->
    <header class="unified-navbar">
        <div class="unified-navbar-container">
            <div class="unified-navbar-left">
                <a href="/" class="unified-navbar-brand">
                    <i class="fas fa-briefcase"></i>
                    <span>AI超级面试官平台</span>
                </a>
            </div>
            
            <div class="unified-navbar-center">
                <nav class="unified-navbar-menu">
                    <a href="/" class="unified-nav-item">首页</a>
                    <a href="/chat" class="unified-nav-item">
                        <i class="fas fa-robot"></i>
                        AI智能助手
                    </a>
                    <a href="/interview" class="unified-nav-item active">
                        <i class="fas fa-clipboard-question"></i>
                        模拟面试题
                    </a>
                    <a href="/job-search" class="unified-nav-item">
                        <i class="fas fa-search"></i>
                        职位搜索
                    </a>
                </nav>
            </div>
            
            <div class="unified-navbar-right" id="navbar-right">
                <a href="/login" class="unified-nav-item">
                    <i class="fas fa-sign-in-alt"></i>
                    登录
                </a>
                <a href="/register" class="unified-nav-item">
                    <i class="fas fa-user-plus"></i>
                    注册
                </a>
            </div>
        </div>
    </header>

    <div class="container">
        <div class="header">
            <a href="/interview" class="back-button">
                <i class="fas fa-arrow-left"></i> 返回面试
            </a>
            <h1><i class="fas fa-history"></i> 面试记录</h1>
            <p>查看您的面试历史记录和答题情况</p>
        </div>
        
        <div class="content">
            <div class="loading" id="loadingState">
                正在加载面试记录...
            </div>
            
            <div id="recordsList" style="display: none;">
                <!-- 记录将通过JavaScript动态生成 -->
            </div>
            
            <div class="no-records" id="noRecords" style="display: none;">
                <div class="no-records-icon">📝</div>
                <p>您还没有完成的面试记录</p>
                <a href="/interview" class="btn-primary">开始面试</a>
            </div>
        </div>
    </div>
    
    <script src="/vendors/jquery/jquery.min.js"></script>
    <script src="/js/auth.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            loadRecords();
        });
        
        async function loadRecords() {
            try {
                const token = localStorage.getItem('token');
                if (!token) {
                    window.location.href = '/login';
                    return;
                }
                
                const response = await fetch('/interview/records/list', {
                    method: 'GET',
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                });
                
                const data = await response.json();
                console.log('API响应数据:', data);
                
                if (data.success) {
                    console.log('面试记录数量:', data.records ? data.records.length : 0);
                    displayRecords(data.records);
                } else {
                    if (response.status === 401) {
                        localStorage.removeItem('token');
                        window.location.href = '/login';
                    } else {
                        alert('加载失败: ' + data.message);
                    }
                }
                
            } catch (error) {
                console.error('加载面试记录失败:', error);
                alert('网络错误，请稍后重试');
            } finally {
                document.getElementById('loadingState').style.display = 'none';
            }
        }
        
        function displayRecords(records) {
            const recordsList = document.getElementById('recordsList');
            const noRecords = document.getElementById('noRecords');
            
            if (!records || records.length === 0) {
                noRecords.style.display = 'block';
                return;
            }
            
            let html = '';
            records.forEach((record, index) => {
                const session = record.session;
                const answers = record.answers || [];
                
                html += `
                    <div class="record-card">
                        <div class="record-header">
                            <div class="info-item">
                                <div class="info-label">目标岗位</div>
                                <div class="info-value">${session.targetPosition}</div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">工作经验</div>
                                <div class="info-value">${session.workExperience}</div>
                            </div>
                            <div class="info-item">
                                <div class="info-label">完成时间</div>
                                <div class="info-value">${formatDateTime(session.submitTime)}</div>
                            </div>
                            <div class="record-actions">
                                <button class="btn-expand" onclick="toggleRecord(${index})">
                                    <i class="fas fa-chevron-down" id="icon-${index}"></i> 详情
                                </button>
                                ${generateEvaluationButton(session)}
                                <button class="btn-delete" onclick="deleteRecord('${session.sessionId}')">
                                    <i class="fas fa-trash"></i> 删除
                                </button>
                            </div>
                        </div>
                        <div class="record-content" id="content-${index}">
                            <div class="session-details">
                                <h4><i class="fas fa-info-circle"></i> 面试详情</h4>
                                <div class="detail-grid">
                                    <div class="detail-item">
                                        <div class="info-label">技能描述</div>
                                        <div class="detail-value">${session.skills}</div>
                                    </div>
                                    <div class="detail-item">
                                        <div class="info-label">答题进度</div>
                                        <div class="detail-value">${record.answeredCount || 0}/${answers.length} 题</div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="answers-section">
                                <h4><i class="fas fa-clipboard-list"></i> 题目与答案 (已回答: ${record.answeredCount || 0}/${answers.length}题)</h4>
                                ${generateAnswersHtml(answers)}
                            </div>
                        </div>
                    </div>
                `;
            });
            
            recordsList.innerHTML = html;
            recordsList.style.display = 'block';
        }
        
        function generateAnswersHtml(answers) {
            if (!answers || answers.length === 0) {
                return '<p style="text-align: center; color: #888; padding: 20px;">暂无答题记录</p>';
            }
            
            let html = '';
            answers.forEach((answer, index) => {
                html += `
                    <div class="answer-item">
                        <div class="answer-question">
                            <strong>题目 ${index + 1}:</strong> ${answer.questionTitle || answer.questionContent}
                        </div>
                        <div class="answer-content">${answer.answerContent || '未回答'}</div>
                    </div>
                `;
            });
            
            return html;
        }
        
        function generateEvaluationButton(session) {
            // 默认显示评估按钮
            let buttonHtml = `<button class="btn-evaluate" onclick="evaluateInterview('${session.sessionId}')">
                <i class="fas fa-star"></i> 评估
            </button>`;

            // 根据评估状态决定显示哪个按钮
            // 注意：只有明确的evaluationStatus='评估完成'才显示查看分析按钮
            if (session.evaluationStatus === '评估完成' && session.totalScore && session.totalScore > 0) {
                buttonHtml = `<button class="btn-view-analysis" onclick="viewAnalysis('${session.sessionId}')">
                    <i class="fas fa-chart-line"></i> 查看分析
                </button>`;
            } else if (session.evaluationStatus === '评估中') {
                buttonHtml = `<button class="btn-evaluating" disabled>
                    <i class="fas fa-spinner fa-spin"></i> 评估中...
                </button>`;
            } else if (session.evaluationStatus === '评估失败') {
                buttonHtml = `<button class="btn-evaluate" onclick="evaluateInterview('${session.sessionId}')">
                    <i class="fas fa-redo"></i> 重新评估
                </button>`;
            } else {
                // 对于evaluationStatus为null/undefined或其他值的情况，都显示评估按钮
                // 这包括了数据库中没有evaluation_status字段的情况
                buttonHtml = `<button class="btn-evaluate" onclick="evaluateInterview('${session.sessionId}')">
                    <i class="fas fa-star"></i> 评估
                </button>`;
            }
            
            return buttonHtml;
        }
        
        async function evaluateInterview(sessionId) {
            if (!confirm('确定要评估这次面试吗？评估过程可能需要几分钟时间。')) {
                return;
            }
            
            try {
                const token = localStorage.getItem('token');
                const button = event.target;
                const originalText = button.innerHTML;
                
                // 显示加载状态
                button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 评估中...';
                button.disabled = true;
                
                const response = await fetch('/interview/evaluate', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + token
                    },
                    body: JSON.stringify({
                        sessionId: sessionId
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    alert('✅ 面试评估完成！');
                    // 重新加载页面以显示最新状态
                    setTimeout(() => {
                        location.reload();
                    }, 1000);
                } else {
                    alert('❌ 评估失败: ' + data.message);
                    button.innerHTML = originalText;
                    button.disabled = false;
                }
                
            } catch (error) {
                console.error('评估失败:', error);
                alert('❌ 网络错误，请稍后重试');
                const button = event.target;
                button.innerHTML = '<i class="fas fa-star"></i> 评估';
                button.disabled = false;
            }
        }
        
        async function viewAnalysis(sessionId) {
            try {
                const token = localStorage.getItem('token');
                if (!token) {
                    alert('请先登录');
                    return;
                }
                
                // 首先验证用户是否有权限访问此分析结果
                const checkResponse = await fetch(`/interview/analysis/${sessionId}`, {
                    method: 'GET',
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                });
                
                if (checkResponse.ok) {
                    // 有权限访问，构建带token的URL并跳转
                    const analysisUrl = `/interview/analysis?sessionId=${sessionId}&token=${encodeURIComponent(token)}`;
                    window.open(analysisUrl, '_blank');
                } else {
                    const errorData = await checkResponse.json();
                    alert('无法访问分析结果: ' + (errorData.message || '权限验证失败'));
                }
                
            } catch (error) {
                console.error('访问分析结果失败:', error);
                alert('网络错误，请稍后重试');
            }
        }
        
        function toggleRecord(index) {
            const content = document.getElementById(`content-${index}`);
            const icon = document.getElementById(`icon-${index}`);
            
            if (content.classList.contains('expanded')) {
                content.classList.remove('expanded');
                icon.className = 'fas fa-chevron-down';
            } else {
                content.classList.add('expanded');
                icon.className = 'fas fa-chevron-up';
            }
        }
        
        async function deleteRecord(sessionId) {
            if (!confirm('确定要删除这条面试记录吗？删除后无法恢复。')) {
                return;
            }
            
            try {
                const token = localStorage.getItem('token');
                const response = await fetch(`/interview/records/${sessionId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                });
                
                const data = await response.json();
                
                if (data.success) {
                    alert('✅ 删除成功');
                    setTimeout(() => {
                        location.reload();
                    }, 1000);
                } else {
                    alert('❌ 删除失败: ' + data.message);
                }
                
            } catch (error) {
                console.error('删除记录失败:', error);
                alert('❌ 网络错误，请稍后重试');
            }
        }
        
        function formatDateTime(dateTimeStr) {
            if (!dateTimeStr) return '未知';
            
            try {
                const date = new Date(dateTimeStr);
                return date.toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit'
                });
            } catch (error) {
                return dateTimeStr;
            }
        }
    </script>
</body>
</html> 